# koroFileHeader at Yungoal acer
# Create: 2022-10-08 13:55:24
# LastEdit: 2022-11-21 17:12:11
"""说明暂无"""
__author__ = '749B'

from decimal import Decimal, InvalidOperation

from django.conf import settings
from django.contrib import admin
from django.core.mail import send_mail

from tasks.cpp_count import CppSync
from tasks.report_sync import ReportSync
from utils.azure_ea import AzureBillingClient
from utils.vault import decrypt

from . import models
# Register your models here.
class AccountAdmin(admin.ModelAdmin):
    list_display = ('name', 'enrollment', 'report_sync_status', 'sync_cpp_type_status')
    fieldsets = (
        (None, {
            'fields': ('name', 'enrollment')
        }),
        ('Secret', {
            'classes': ('collapse',),
            'fields': ('access_key',)
        })
    )
    actions = ('sync_report', 'sync_cpp_type')

    @admin.display(description='同步报表')
    def report_sync_status(self, obj):
        return ReportSync.get_task_status('ReportSync', obj.name)

    @admin.action(description='同步报表')
    def sync_report(self, request, queryset):
        for account in queryset:
            enrollment = account.enrollment
            access_key = decrypt(account.access_key, settings.VAULT_PASSWORD)
            account_name = account.name
            assert access_key
            client = AzureBillingClient(enrollment, access_key, name=account_name)
            task = ReportSync(client)  # 默认贵族，按月度的增量同步，第一次会从最早的日期开始
            task_started = task.start()
            if task_started:
                self.message_user(request, f'同步报表开始: {account_name}', 'success')
            else:
                self.message_user(
                    request, 
                    f'任务未开始: {account_name} {task.task_start_msg or ""}', 
                    'warning')

    @admin.display(description='自动录入CPP数量')
    def sync_cpp_type_status(self, obj):
        return CppSync.get_task_status('CppSync', obj.name)

    @admin.action(description='自动录入CPP数量')
    def sync_cpp_type(self, request, queryset):
        for account in queryset:
            account_name = account.name
            task = CppSync(account_name=account_name)
            task_started = task.start()
            if task_started:
                self.message_user(request, f'自动录入CPP数量开始: {account_name}', 'success')
            else:
                self.message_user(
                    request, 
                    f'任务未开始: {account_name} {task.task_start_msg or ""}', 
                    'warning')


class SubscriptionsAdmin(admin.ModelAdmin):
    list_display = ('name', 'guid', 'usage_budget', 'usage_threshold', 'usage_alarm', 'email')
    readonly_fields = ('name', 'guid', 'short_id')
    list_editable = ('usage_budget', 'usage_threshold', 'usage_alarm', 'email')
    search_fields = ('name',)
    actions = ('send_test_mail', 'bulk_change_usage_budget')
    actions_bar = True  # 在动作栏的后面是否追加自定义的文本框用于填写actions需要的参数

    @admin.action(description='发送测试邮件')
    def send_test_mail(self, request, queryset):
        subject = '测试邮件'
        from_email = 'bk@monitor.yungoal.com'
        for sub in queryset:
            recipient_list = [email.lstrip() for email in sub.email.split(';') if email]
            if not recipient_list:
                self.message_user(request, f'没有设置通知人: {sub.name} 收件人列表为空', 'warning')
                continue
            message = f'您是订阅 {sub.name} 的通知人'
            try:
                send_mail(subject, message, from_email, recipient_list, fail_silently=False)
            except Exception as e:
                self.message_user(request, f'邮件发送失败: {e}', 'warning')
            else:
                self.message_user(request, f'邮件发送成功: 请通知收件人确认 {sub.email}', 'success')

    @admin.action(description='批量设置预算')
    def bulk_change_usage_budget(self, request, queryset):
        # 确认有提供参数
        value = request.POST.get('action_var')
        if not value:
            self.message_user(request, '没有提供要修改的值', 'warning')
            return
        # 确认提供的参数是数值
        try:
            value = Decimal(value).quantize(Decimal(".01")) 
        except InvalidOperation:
            self.message_user(request, f'请输入数值: {value}', 'warning')
            return
        # 设置完成后做批量修改
        for sub in queryset:
            sub.usage_budget = value
        models.Subscriptions.objects.bulk_update(queryset, ['usage_budget'])
    

class CppProductAdmin(admin.ModelAdmin):
    list_display = (
        'product', 'locked',
        'cpp_count', 'value_of_measure', 'unit_price',
        'price_display')
    search_fields = ('product',)
    readonly_fields = (
        'product',
        'meter_sub_category', 'meter_name', 'meter_region', 
        'price')
    list_editable = ('locked', 'cpp_count', 'value_of_measure', 'unit_price')
    list_filter = ('cpp_count', 'meter_sub_category', 'meter_name', 'meter_region')


admin.site.register(models.Account, AccountAdmin)
admin.site.register(models.Summary)
admin.site.register(models.Subscriptions, SubscriptionsAdmin)
admin.site.register(models.CppProduct, CppProductAdmin)
